/**
 * Created by Ysssssss on 2021/5/13.
 */

import React, { PureComponent } from 'react'
import {connect} from "react-redux";
import {getHistoryMatchParams, getQuery, handleQueryEqual, setQuery} from "@utils/setUrlQuery";
import PageBackHeader from "@common/PageBackHeader";
import {MultiSelectProductModal, MultiSelectStoreModal} from "@common/presentational/MultiSelectModal";
import {EditSupplyGroupModal} from "@components/productCenter/modal/SupplyGroupModal";
import {Select, Button} from "antd";
import SearchInput from "@common/presentational/SearchInput";
import {
    getSupplyGroupProductList,
    getSupplyGroupDetailInfo,
    getProductTypeSelection,
    bulkAddProductToSupplyGroup,
    bulkDeleteProductFromSupplyGroup,
    editSupplyGroupInfoPrice,
    setSupplyGroupRelatedStores
} from "@sagas/productCenter";
import CustomizeTableProvide, {CustomizeTable, CustomizeTablePagination} from "@common/presentational/CustomizeTable";
import {priceFenToYuan} from "@utils/priceConversion";
import DoubleCheck from "@common/presentational/DoubleCheck";
import {withRouter} from "react-router-dom";
import BilinIcon from "@common/presentational/BilinIcon";
import {SingleEditProductPriceModal} from "@common/presentational/EditProductPriceModal";

@connect(({ productCenter }) => ({
    supplyGroupMap: productCenter.supplyGroupMap,
    supplyGroupProductPagination: productCenter.supplyGroupProductPagination,
    productTypeSelection: productCenter.productTypeSelection,
}), {
    getSupplyGroupProductList,
    getSupplyGroupDetailInfo,
    getProductTypeSelection,
    bulkAddProductToSupplyGroup,
    bulkDeleteProductFromSupplyGroup,
    editSupplyGroupInfoPrice,
    setSupplyGroupRelatedStores
})
@withRouter

class SupplyGroupProductPage extends PureComponent {
    constructor(props) {
        super(props);
        const { prodTypeId = '', query = '' } = getQuery(props.history)
        this.state = {
            prodTypeId,
            query: decodeURIComponent(query),
            selectedRows: []
        }

        this.tableRef = React.createRef();
        this.multiSelectStoreModalRef = React.createRef();
        this.multiSelectProductModalRef = React.createRef();
        this.editSupplyGroupModalRef = React.createRef()
        this.singleEditProductPriceModalRef = React.createRef()

        this.columns = [{
            key: 'name',
            dataIndex: 'name',
            title: '商品名称',
            render: (text, record) => ({
                children: text,
                props: record.skus.length <= 1 ? {} : { rowSpan: record.sku_index === 0 ? record.skus.length : 0 }
            })
        }, {
            key: 'prod_type_name',
            dataIndex: 'prod_type_name',
            title: '分类',
            render: (text, record) => ({
                children: text,
                props: record.skus.length <= 1 ? {} : { rowSpan: record.sku_index === 0 ? record.skus.length : 0 }
            })
        }, {
            key: 'sku_name',
            dataIndex: 'sku_name',
            title: '规格',
        }, {
            key: 'sku_price',
            dataIndex: 'sku_price',
            title: '价格',
            render: text => `￥${priceFenToYuan(text)}`
        }, {
            key: 'operation',
            dataIndex: 'operation',
            title: '操作',
            render: (text, record) => ({
                children: (
                    <div className="flex-vertical-center">
                        <div className="mgr-8 ft-hover" onClick={this.editProductPrice.bind(this, record)}>修改价格</div>
                        <DoubleCheck title="是否确认删除" onClick={this.deleteProduct.bind(this, record.id)}>
                            <div className="mgr-8 ft-hover">删除</div>
                        </DoubleCheck>
                    </div>
                ),
                props: record.skus.length <= 1 ? {} : { rowSpan: record.sku_index === 0 ? record.skus.length : 0 }
            })
        }]
    }

    componentDidMount () {
        this.props.getProductTypeSelection()
        this.getSupplyGroupDetailInfo()
    }

    handleSelectRowsChange (rows) {
        this.setState({
            selectedRows: rows
        })
    }

    getSupplyGroupDetailInfo () {
        const { id } = getHistoryMatchParams(this.props)
        this.props.getSupplyGroupDetailInfo({
            id
        })
    }

    getTableInfo ({ current, pageSize } = this.paginationInfo) {
        this.paginationInfo = { current, pageSize }
        const { id } = getHistoryMatchParams(this.props)
        const { query, prodTypeId } = this.state
        this.props.getSupplyGroupProductList({
            menuId: id,
            query,
            prodTypeId,
            pageNo: current,
            pageSize,
        })
        this.setUrlQuery()
    }

    setUrlQuery () {
        const { current, pageSize } = this.paginationInfo
        const { history } = this.props
        const { query, prodTypeId } = this.state
        let params = {
            query,
            prodTypeId,
            pageNo: current,
            pageSize,
        }
        handleQueryEqual(params, history) || setQuery(params, history)
    }

    handleValueChange (key, value) {
        this.setState({
            [key]: value
        }, this.initTable)
    }

    initTable () {
        this.tableRef.current?.initPage()
    }

    editRelatedStores (storeIds) {
        const { id } = getHistoryMatchParams(this.props)
        this.multiSelectStoreModalRef.current?.show({
            initSelectedStores: storeIds.map(store => ({ store_id: store.id, store_name: store.name })),
            id
        })
    }

    editSupplyGroupInfo () {
        const { id } = getHistoryMatchParams(this.props)
        this.editSupplyGroupModalRef.current?.show({ id })
    }

    editProductPrice (record) {
        this.singleEditProductPriceModalRef.current?.show({
            productInfo: record
        })
    }

    handleProductPriceChange ({ id: prodId, skus }, callback) {
        const { id } = getHistoryMatchParams(this.props)
        this.props.editSupplyGroupInfoPrice({
            menuId: id,
            prodId: prodId,
            skus
        }, () => {
            this.getTableInfo()
            callback && callback()
        })
    }

    handleProductChange (productInfoList) {
        const { id } = getHistoryMatchParams(this.props)
        this.props.bulkAddProductToSupplyGroup({
            menuId: id,
            prodIds: productInfoList.map(prod => prod.id)
        }, () => {
            this.getTableInfo()
        })
    }

    bulkDeleteProduct () {
        const { id } = getHistoryMatchParams(this.props)
        const { selectedRows } = this.state
        this.props.bulkDeleteProductFromSupplyGroup({
            menuId: id,
            prodIds: selectedRows.map(row => row.id)
        })
    }

    deleteProduct (prodId) {
        const { id } = getHistoryMatchParams(this.props)
        this.props.bulkDeleteProductFromSupplyGroup({
            menuId: id,
            prodIds: [prodId]
        })

    }

    reformDataSourceSkus (dataSource) {
        let ret = []
        dataSource.forEach(data => {
            data.skus.forEach((sku, index) => {
                ret.push({
                    ...data,
                    sku_name: sku.name || '--',
                    sku_price: sku.price,
                    sku_index: index,
                    key: index === 0 ? data.id : `${data.id}_${sku.id}`
                })
            })
        })
        return ret
    }

    handleStoreChange (stores, params) {
        this.props.setSupplyGroupRelatedStores({
            id: params.id,
            storeIds: stores.map(store => store.store_id)
        }, () => {
            this.getSupplyGroupDetailInfo()
        })
    }

    showAddProductModal () {
        this.multiSelectProductModalRef.current?.show()
    }

    render () {
        const { supplyGroupProductPagination, productTypeSelection, supplyGroupMap } = this.props
        const { query, prodTypeId, selectedRows } = this.state
        const { id } = getHistoryMatchParams(this.props)
        const supplyGroupInfo = supplyGroupMap[id]

        return supplyGroupInfo ? (
            <div className="bilin-web">
                <PageBackHeader title="供货中心" backUrl="/product-center-type/supply-group"/>
                <div className="bilin-web-body table-page supply-group-product-page">
                    <div className="table-scroll-container">
                        <div className="related-stores">
                            <div className="stores-list">应用店铺({supplyGroupInfo.stores.length}): {supplyGroupInfo.stores.map(store => store.name).join(', ')}</div>
                            <div className="flex-vertical-center">
                                <span className="cur-poi clr-green"
                                      onClick={this.editRelatedStores.bind(this, supplyGroupInfo.stores)}
                                >应用</span>
                                <span className="cur-poi clr-green mgl-24"
                                      onClick={this.editSupplyGroupInfo.bind(this)}
                                >设置</span>
                            </div>
                        </div>
                        <div className="table-params page-params flex-row-between">
                            { selectedRows.length ? (
                                <div className="flex-vertical-center">
                                    <DoubleCheck title="是否确认从供货组中删除已选商品" onClick={this.bulkDeleteProduct.bind(this)}>
                                        <Button type="danger" className="button-small">
                                            <span className="mgl-8">删除</span>
                                        </Button>
                                    </DoubleCheck>
                                </div>
                            ): (
                                <Button type="primary" className="button-small" onClick={this.showAddProductModal.bind(this)}>
                                    <BilinIcon type="plus"/>
                                    <span className="mgl-8">从商品库添加</span>
                                </Button>
                            ) }
                            <div className="flex-vertical-center">
                                <Select className="mgr-16"
                                        style={{width: '140px'}}
                                        onChange={this.handleValueChange.bind(this, 'prodTypeId')}
                                        value={prodTypeId}
                                >
                                    <Select.Option key={0} value="">全部</Select.Option>
                                    { productTypeSelection.map(productTypeGroup => (
                                        <Select.OptGroup key={productTypeGroup.id} label={productTypeGroup.name}>
                                            { productTypeGroup.subs.map(productType => (
                                                <Select.Option
                                                    key={productType.id}
                                                    value={productType.id}
                                                >
                                                    { productType.name }
                                                </Select.Option>
                                            )) }
                                        </Select.OptGroup>
                                    ))}
                                </Select>
                                <SearchInput style={{width: 240}}
                                             onChange={this.handleValueChange.bind(this, 'query')}
                                             initValue={query}
                                             value={query}
                                             placeholder="商品名称"
                                />
                            </div>
                        </div>
                        <CustomizeTableProvide ref={this.tableRef} tableKey="supplyGroupProductList" onChange={this.getTableInfo.bind(this)}>
                            <div className="table-list">
                                <CustomizeTable
                                    columns={this.columns}
                                    dataSource={this.reformDataSourceSkus(supplyGroupProductPagination.prods || [])}
                                    pagination
                                    selectionInfo={{
                                        keyValue: 'key',
                                        onChange: this.handleSelectRowsChange.bind(this),
                                        renderCell: (checked, record, index, originNode) => ({
                                            children: originNode,
                                            props: record.skus.length <= 1 ? {} : { rowSpan: record.sku_index === 0 ? record.skus.length : 0 }
                                        })
                                    }}
                                />
                            </div>
                            <div className="table-pagination">
                                <CustomizeTablePagination
                                    total={supplyGroupProductPagination.total}
                                />
                            </div>
                        </CustomizeTableProvide>
                    </div>
                </div>
                <MultiSelectStoreModal
                    ref={this.multiSelectStoreModalRef}
                    title="应用店铺"
                    onChange={this.handleStoreChange.bind(this)}
                />
                <EditSupplyGroupModal ref={this.editSupplyGroupModalRef} callback={this.getSupplyGroupDetailInfo.bind(this)}/>
                <MultiSelectProductModal
                    ref={this.multiSelectProductModalRef}
                    title="添加商品"
                    onChange={this.handleProductChange.bind(this)}
                    excludedMenuId={id}
                />
                <SingleEditProductPriceModal
                    ref={this.singleEditProductPriceModalRef}
                    priceEditAction={this.handleProductPriceChange.bind(this)}
                />
            </div>
        ) : null
    }
}

export default SupplyGroupProductPage